package com.quanta.edaily.Service.impl;

import com.quanta.edaily.Service.FavouriteService;
import com.quanta.edaily.mapper.ArticleMapper;
import com.quanta.edaily.mapper.FavouriteMapper;
import com.quanta.edaily.mapper.UserMapper;
import com.quanta.edaily.pojo.Article;
import com.quanta.edaily.pojo.FavArt;
import com.quanta.edaily.pojo.Favourite;
import com.quanta.edaily.pojo.User;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class FavouriteServiceImpl implements FavouriteService {
    @Resource
    FavouriteMapper favouriteMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    ArticleMapper articleMapper;

    @Override
    public List<FavArt> getSomeByUid(Integer uid) {
        return favouriteMapper.getSomeByUid(uid);
    }

    @Override
    public List<User> getSomeByAid(Integer aid) {
        return favouriteMapper.getSomeByAid(aid);
    }

    @Override
    public Favourite getOne(Integer uid, Integer aid) {
        return favouriteMapper.getOne(uid,aid);
    }

    @Override
    public int add(Integer uid, Integer aid) {
        int i = 0;
        try {
            User user = userMapper.getUserById(uid);
            Article article = articleMapper.getById(aid);
            user.setFavourites(user.getFavourites()==null?1:user.getFavourites()+1);
            article.setLikeCount(article.getLikeCount()==null?1:article.getLikeCount()+1);
            i = favouriteMapper.add(uid,aid);
            userMapper.updateUserById(user);
            articleMapper.updateById(article);
        } catch (Exception e) {
            log.error("业务异常", e);
            return 0;
        }
        if (i!=1) return 0;
        return 1;
    }

    @Override
    public int cancel(Integer uid, Integer aid) {
        int i=0;
        try {
            User user = userMapper.getUserById(uid);
            Article article = articleMapper.getById(aid);
            user.setFavourites(user.getFavourites()==null||user.getFavourites()<1?0:user.getFavourites()-1);
            article.setLikeCount(article.getLikeCount()==null||article.getLikeCount()<1?0:article.getLikeCount()-1);
            userMapper.updateUserById(user);
            articleMapper.updateById(article);
            i = favouriteMapper.cancel(uid, aid);
        } catch (Exception e) {
            log.error("业务异常", e);
            return 0;
        }
        if (i!= 1) return 0;
        return 1;
    }
}
